package domain.dao;

import java.util.logging.Level;
import java.util.logging.Logger;

import main.ServerConfig;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


/**
 * last change:  $Date$
 * by:           $Author$
 * revision:     $Revision$
 *
 */
public abstract class AbstractDao {
//  private static final SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  private static SessionFactory SESSION_FACTORY;
  private ServerConfig serverConfig;

  private static final ThreadLocal session = new ThreadLocal();

  static final Logger logger = Logger.getAnonymousLogger();

  protected AbstractDao() {
    serverConfig = new ServerConfig();
    Configuration configuration = new Configuration().configure();
    configuration.setProperty("hibernate.connection.url", "jdbc:mysql://" + serverConfig.getDatabaseUrl());
    configuration.setProperty("hibernate.connection.password", serverConfig.getDatabasePassword());
    configuration.setProperty("hibernate.connection.username", serverConfig.getDatabaseUsername());
    SESSION_FACTORY = configuration.buildSessionFactory();
  }

  public static Session getSession() {
    Session session = (Session) AbstractDao.session.get();
    if(session == null)
    {
      session = SESSION_FACTORY.openSession();
      AbstractDao.session.set(session);
    }
    return session;
  }

  protected void begin() {
    getSession().beginTransaction();
  }

  protected void commit() {
    getSession().getTransaction().commit();
  }

  protected void rollback() {
    try {
      getSession().getTransaction().rollback();
    }
    catch(HibernateException e) {
      logger.log(Level.WARNING, "Cannot close", e);
    }
    try {
      getSession().close();
    }
    catch(HibernateException e) {
      logger.log(Level.WARNING, "Cannot close", e);
    }
    AbstractDao.session.set(null);
  }

  public static void close() {
    getSession().close();
    AbstractDao.session.set(null);
  }
}
